package domein.server;


import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JTextPane;
import javax.swing.text.StyledDocument;

import domein.client.IClient;

public class MyBuilder implements IBuilder, Serializable
{
	public List<IClient> observers;
	private StyledDocument styledDoc;
	private Map<Integer, Boolean> hasChanged;

	private int count = 0;
	
	public MyBuilder() {
		
		hasChanged = new HashMap<Integer, Boolean>();
		styledDoc = new JTextPane().getStyledDocument();
		observers = new ArrayList<IClient>();
	}
	
	@Override
	public StyledDocument read(int clientID)
	{
		hasChanged.put(clientID, false);
		System.out.println(clientID +" read");
		return styledDoc;
		
	}
	
	@Override
	public void write(int clientID, StyledDocument theString) throws RemoteException, IllegalStateException
	{
		System.out.println(clientID + " write");
		if(hasChanged(clientID)== false)
		{
			styledDoc = theString;
			
			
			for (int id :hasChanged.keySet())
			{
				hasChanged.put(id, true);
			}
			hasChanged.put(clientID, false);
			notifyObservers(clientID);
		}else{System.out.println("conflict"); throw new IllegalStateException();}
	}
	
	@Override
	public boolean hasChanged(int serverID)
	{
		return hasChanged.get(serverID);
	}

	@Override
	public int getID()  {
		count++;
		return count;
	}

	@Override
	public void addObserver(IClient obs) {
		observers.add(obs);
	}
	
	@Override
	public void notifyObservers(int clientID) throws RemoteException
	{
		for (IClient o : observers)
		{
			if (o.getID() != clientID) o.update();
		}
	}

	@Override
	public void removeOserver(int clientID) throws RemoteException {
		// TODO Auto-generated method stub
		Iterator<IClient> it = observers.iterator();
		while(it.hasNext())
		{
			if(it.toString().equals(clientID))
			{
				it.remove();
			}
		}
	}


	
}
